/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package application;

/**
 *
 * @author Hui
 */

import java.sql.*;

import java.io.*;
 import com.sun.image.codec.jpeg.*;
 import javax.imageio.*;
 import java.awt.image.*;


public class DownloadImage {


    private Connection conn = null;
    private BufferedInputStream inputImage = null;
    private String driverName = "com.mysql.jdbc.Driver";
    private String dbURL = "jdbc:mysql://194.47.47.18:3306/DA5221_GRP8";
    private String userID = "DA5221_GRP8";
    private String passwd = "iXiRGq";
    private String photopath = "No image";
    private String name;

    public String download(String name) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

        String showImage = "select * from person where UserName ='" + name + "'";
        try {
            Class.forName(driverName).newInstance();
            conn = DriverManager.getConnection(dbURL, userID, passwd);

            Statement st = conn.createStatement();
            ResultSet rs = st.executeQuery(showImage);
            while (rs.next()) {
                Blob blob = (Blob) rs.getBlob("image");
                inputImage = new BufferedInputStream(blob.getBinaryStream());
            }
           

            BufferedImage image = null;
            image = ImageIO.read(inputImage);
            photopath = "img/"+name+".jpg";
            System.out.println("下载图片 : "+photopath );
        //     this.name = photopath;
            FileOutputStream fos = new FileOutputStream(photopath);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fos);
            encoder.encode(image);
            fos.close();

        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();


        }
        return photopath;
    }
  


}
